import 'dart:io';
import 'dart:async';

import 'package:appsflyer_sdk/appsflyer_sdk.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:video_player/video_player.dart';

import '../utils/appsflyer_event_manager.dart';

AppsflyerSdk? appsflyerSdk;

class SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with TickerProviderStateMixin {
  // 首次启动检测常量
  static const String _firstLaunchKey = 'has_launched_before';

  // 视频播放器控制器
  VideoPlayerController? _videoController;
  bool _isVideoInitialized = false;

  // 动画控制器
  late AnimationController _fadeController;
  late AnimationController _pulseController;
  late AnimationController _scaleController;

  // 动画
  late Animation<double> _fadeAnimation;
  late Animation<double> _pulseAnimation;
  late Animation<double> _scaleAnimation;

  // 计时器
  Timer? _countdownTimer;
  Timer? _mainTimer;

  // 状态变量
  int _countdownSeconds = 8; // 改为8秒倒计时
  bool _showEnterButton = false;
  bool _showSkipButton = false;
  bool _appsFlyerInitialized = false;
  bool _isFirstLaunch = true;
  bool _showVideoBackground = false;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _checkFirstLaunch();
  }

  void _initAnimations() {
    // 淡入动画控制器
    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 500),
      vsync: this,
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeOut),
    );

    // 呼吸动画控制器
    _pulseController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    _pulseAnimation = Tween<double>(begin: 1.0, end: 1.05).animate(
      CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
    );

    // 缩放动画控制器
    _scaleController = AnimationController(
      duration: const Duration(milliseconds: 100),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(begin: 1.0, end: 0.95).animate(
      CurvedAnimation(parent: _scaleController, curve: Curves.easeInOut),
    );
  }

  Future<void> _initVideoPlayer() async {
    try {
      _videoController =
          VideoPlayerController.asset('assets/images/iuvideo.MOV');
      await _videoController!.initialize();

      setState(() {
        _isVideoInitialized = true;
      });

      // 设置视频循环播放
      _videoController!.setLooping(true);
      // 开始播放视频
      _videoController!.play();

      print("🎬 视频初始化成功并开始播放");
    } catch (e) {
      print("❌ 视频初始化失败: $e");
      // 如果视频初始化失败，显示占位图片
      setState(() {
        _isVideoInitialized = false;
      });
    }
  }

  Future<void> _checkFirstLaunch() async {
    final prefs = await SharedPreferences.getInstance();
    final isFirstLaunch = prefs.getBool(_firstLaunchKey) ?? true;
    setState(() {
      _isFirstLaunch = isFirstLaunch;
      // _showVideoBackground = true;
      // _showSkipButton = true; // 立即显示跳过按钮
    });
    if (!isFirstLaunch) {
      print("⚡ 非首次启动，直接跳转到主应用");
      await _initAppsFlyer();
      // _navigateToHome();
      return;
    }

    print("🎬 首次启动，显示视频启动页");
    setState(() {
      // _isFirstLaunch = isFirstLaunch;
      _showVideoBackground = true;
      _showSkipButton = true; // 立即显示跳过按钮
    });

    // 初始化视频播放器
    await _initVideoPlayer();

    _startCountdown();
    _startMainTimer();
    _initProcess();
  }

  void _startCountdown() {
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdownSeconds > 0) {
        setState(() {
          _countdownSeconds--;
        });
      } else {
        timer.cancel();
        // 倒计时结束后自动进入应用
        // _onEnterButtonTap();
      }
    });
  }

  void _startMainTimer() {
    // 7秒后显示进入按钮（比倒计时早1秒）
    _mainTimer = Timer(const Duration(seconds: 7), () {
      _showEnterButtonIfReady();
    });
  }

  void _showSkipButtonWithAnimation() {
    // 这个方法现在主要用于显示进入按钮
    _showEnterButtonIfReady();
  }

  void _showEnterButtonIfReady() {
    if (_appsFlyerInitialized || _countdownSeconds <= 1) {
      setState(() {
        _showEnterButton = true;
      });
      _fadeController.forward();

      // 延迟启动呼吸动画
      Future.delayed(const Duration(milliseconds: 700), () {
        if (mounted) {
          _pulseController.repeat(reverse: true);
        }
      });
    }
  }

  Future<void> _initProcess() async {
    final prefs = await SharedPreferences.getInstance();
    final userType = prefs.getString('user_type');

    if (userType != null) {
      _initAppsFlyer();
    } else {
      _requestATTPermission();
    }
  }

  Future<void> _requestATTPermission() async {
    if (Platform.isIOS) {
      final status =
          await AppTrackingTransparency.requestTrackingAuthorization();
      print("🔒 ATT权限状态: $status");
    }
    _initAppsFlyer();
  }

  Future<void> _initAppsFlyer() async {
    final AppsFlyerOptions appsFlyerOptions = AppsFlyerOptions(
      afDevKey: "pJpKGnELxYueV2QxpgztDh",
      appId: "6738265376",
      showDebug: true,
      timeToWaitForATTUserAuthorization: 15,
      disableAdvertisingIdentifier: false,
      disableCollectASA: false,
      manualStart: false,
    );

    appsflyerSdk = AppsflyerSdk(appsFlyerOptions);

    // 🔥 关键修复：将SDK实例传递给EventManager
    AppsFlyerEventManager.initialize(appsflyerSdk!);

    appsflyerSdk!.onInstallConversionData((data) {
      print("📊 AppsFlyer安装转化数据: $data");
      _handleInstallConversionData(data);
    });

    appsflyerSdk!.onDeepLinking((data) {
      print("🔗 AppsFlyer深度链接: $data");
    });

    appsflyerSdk!.initSdk(
      registerConversionDataCallback: true,
      registerOnAppOpenAttributionCallback: true,
      registerOnDeepLinkingCallback: true,
    );

    // 7秒后强制显示进入按钮
    Timer(const Duration(seconds: 7), () {
      if (!_appsFlyerInitialized) {
        setState(() {
          _appsFlyerInitialized = true;
        });
        _showEnterButtonIfReady();
      }
    });
  }

  void _navigateToHome() {
    _cleanupTimers();
    if (mounted) {
      context.go('/');
    }
  }

  void _cleanupTimers() {
    _countdownTimer?.cancel();
    _mainTimer?.cancel();
  }

  void _onEnterButtonTap() async {
    _scaleController.forward().then((_) {
      _scaleController.reverse();
    });

    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool(_firstLaunchKey, false);

    Future.delayed(const Duration(milliseconds: 200), () {
      _navigateToHome();
    });
  }

  void _handleInstallConversionData(Map<dynamic, dynamic> data) {
    if (data['status'] == 'success') {
      // 2. 获取 payload 数据
      final payload = data['payload'];

      // 3. 关键判断：af_status 是 "Organic" 还是 "Non-organic"
      final afStatus = payload['af_status'];

      if (afStatus == 'Organic') {
        // print("🟢 这是一个自然量（用户主动搜索下载）");
        _setUserType('organic');
        // _navigateToHome();
      } else if (afStatus == 'Non-organic') {
        // print("🔴 这是一个非自然量（通过广告/推广渠道带来的安装）");

        // 4. 如果是非自然量，还可以获取渠道信息（可选）
        final mediaSource = payload['media_source']; // 渠道来源（如 google、facebook）
        // final campaign = payload['campaign']; // 推广活动名称
        // print("📈 渠道来源: $mediaSource, 推广活动: $campaign");

        _setUserType('non_organic', mediaSource: mediaSource?.toString());
        // _navigateToHome();
      } else {
        // print("⚠️ 未知的 af_status: $afStatus");
        _setUserType('organic'); // 默认设置为自然量
        // _navigateToHome();
      }
      setState(() {
        _appsFlyerInitialized = true;
      });
      if (_isFirstLaunch == false) {
        _navigateToHome();
      } else {
        _showEnterButtonIfReady();
      }
    } else {
      // print("❌ 获取安装转化数据失败");
      _setUserType('organic'); // 默认设置为自然量
      // _navigateToHome();
      setState(() {
        _appsFlyerInitialized = true;
      });
      if (_isFirstLaunch == false) {
        _navigateToHome();
      } else {
        _showEnterButtonIfReady();
      }
    }
  }

  void _setUserType(String type, {String? mediaSource}) async {
    print("💾 设置用户类型: $type");
    if (mediaSource != null) {
      print("💾 媒体来源: $mediaSource");
    }

    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('user_type', type);
    if (mediaSource != null) {
      await prefs.setString('media_source', mediaSource);
    }

    // 记录设置的comicType值
    final comicType = type == 'organic' ? '0' : '1';
    print("💾 对应的comicType值: $comicType");
  }

  @override
  void dispose() {
    _cleanupTimers();
    _fadeController.dispose();
    _pulseController.dispose();
    _scaleController.dispose();
    _videoController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          // 视频背景或占位图片
          _buildVideoBackground(),

          // 渐变遮罩
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.black.withOpacity(0.3),
                  Colors.black.withOpacity(0.7),
                ],
              ),
            ),
          ),

          // 主要内容
          SafeArea(
            child: Column(
              children: [
                // 顶部跳过按钮
                if (_showSkipButton) _buildSkipButton(),

                const Spacer(),

                // 中心Logo区域
                _buildCenterContent(),

                const Spacer(),

                // 底部按钮区域
                _buildBottomContent(),

                const SizedBox(height: 50),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVideoBackground() {
    if (_isVideoInitialized && _videoController != null) {
      return SizedBox.expand(
        child: FittedBox(
          fit: BoxFit.cover,
          child: SizedBox(
            width: _videoController!.value.size.width,
            height: _videoController!.value.size.height,
            child: VideoPlayer(_videoController!),
          ),
        ),
      );
    } else {
      // 显示占位图片
      return Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/laun.png'),
            fit: BoxFit.cover,
          ),
        ),
      );
    }
  }

  Widget _buildSkipButton() {
    return Padding(
      padding: const EdgeInsets.all(20.0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          GestureDetector(
            onTap: _countdownSeconds <= 0 ? _onEnterButtonTap : null,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              decoration: BoxDecoration(
                color: Colors.black.withOpacity(0.5),
                borderRadius: BorderRadius.circular(20),
                border: Border.all(color: Colors.white.withOpacity(0.3)),
              ),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    _countdownSeconds <= 0 ? 'Skip' : '${_countdownSeconds}s',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  const SizedBox(width: 4),
                  const Icon(
                    Icons.skip_next,
                    color: Colors.white,
                    size: 16,
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCenterContent() {
    return Center(
      child: Column(
        children: [
          // 应用名称
          const Text(
            'Fun Toon',
            style: TextStyle(
              fontSize: 32,
              fontWeight: FontWeight.bold,
              color: Colors.white,
              letterSpacing: 2,
              shadows: [
                Shadow(
                  color: Colors.black54,
                  offset: Offset(0, 2),
                  blurRadius: 4,
                ),
              ],
            ),
          ),

          const SizedBox(height: 10),

          // 副标题
          Text(
            '​Fantastic comics, right at your hands',
            style: TextStyle(
              fontSize: 16,
              color: Colors.white.withOpacity(0.8),
              letterSpacing: 1,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomContent() {
    return Column(
      children: [
        // 进入按钮
        if (_showEnterButton)
          AnimatedBuilder(
            animation: _fadeAnimation,
            builder: (context, child) {
              return Opacity(
                opacity: _fadeAnimation.value,
                child: AnimatedBuilder(
                  animation: _pulseAnimation,
                  builder: (context, child) {
                    return Transform.scale(
                      scale: _pulseAnimation.value,
                      child: AnimatedBuilder(
                        animation: _scaleAnimation,
                        builder: (context, child) {
                          return Transform.scale(
                            scale: _scaleAnimation.value,
                            child: GestureDetector(
                              onTap: _onEnterButtonTap,
                              child: Container(
                                width: 200,
                                height: 56,
                                decoration: BoxDecoration(
                                  gradient: const LinearGradient(
                                    colors: [
                                      Color(0xFF6366F1),
                                      Color(0xFF8B5CF6),
                                    ],
                                  ),
                                  borderRadius: BorderRadius.circular(28),
                                  boxShadow: [
                                    BoxShadow(
                                      color: const Color(0xFF6366F1)
                                          .withOpacity(0.4),
                                      blurRadius: 20,
                                      offset: const Offset(0, 8),
                                    ),
                                  ],
                                ),
                                child: const Center(
                                  child: Text(
                                    'Enter the App',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 18,
                                      fontWeight: FontWeight.w600,
                                      letterSpacing: 1,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          );
                        },
                      ),
                    );
                  },
                ),
              );
            },
          ),
      ],
    );
  }
}
